﻿SmitearWebGL.Core.PoolGroup = Class.extend(
{
	/******** constructor ********/
	
	init : function( size )
	{
		/******** private property ********/
		
		this._maxCount = size;
		this._nextOpen = 0;
		this._totalOpen = this._maxCount;
		this._nextOpenList = new Array( this._maxCount );
		this._memberList = new Array( this._maxCount );

		var i;
		for ( i = 0; i < this._maxCount - 1; ++ i )
		{
			this._nextOpenList[i] = i + 1;
		}
		this._nextOpenList[i] = i;
		
		this._registClass( "SmitearWebGL.Core.PoolGroup" );
	}
	,
	
	/******** public method ********/
	
	destroy : function()
	{
		$THROW( this._totalOpen == this._maxCount, "组不为空,请确保所有资源已被释放" );

		this._nextOpenList = null;
		this._memberList = null;
		this._totalOpen = 0;
		this._nextOpen = 0;
	}
	,
	addMember : function( member )
	{
		var slot = this.nextMember();
		this._memberList[slot] = member;

		return slot;
	}
	,
	nextMember : function()
	{
		$THROW( this._totalOpen != 0, "没有可以打开的槽" );

		// 返回开放列表的第一个数据成员, 并把句柄移动到下一个数据成员
		var slot = this._nextOpen;
		this._nextOpen = this._nextOpenList[slot];
		-- this._totalOpen;

		$THROW( this._nextOpen != SmitearWebGL.Core.PoolGroup.INVALID_INDEX, "开放列表索引无效" );
		$THROW( this.isOpen( slot ), "索引无效" );

		// 把数据成员标识为使用中
		this._nextOpenList[slot] = SmitearWebGL.Core.PoolGroup.INVALID_INDEX;

		return slot;
	}
	,
	removeRember : function( index )
	{
		$THROW( index < this._maxCount, "索引无效" );
		$THROW( ! this.isOpen( index ), "被释放的数据成员正在使用中" );

		this._memberList[index] = null;
		this._nextOpenList[index] = this._totalOpen ? this._nextOpen : index;
		++ this._totalOpen;
		this._nextOpen = index;
	}
	,
	totalOpen : function()
	{
		return this._totalOpen;
	}
	,
	totalUsed : function()
	{
		return this._maxCount - this._totalOpen;
	}
	,
	firstOpen : function()
	{
		return this._nextOpen;
	}
	,
	isOpen : function( index )
	{
		$THROW( index < this._maxCount, "索引无效" );

		return this._nextOpenList[index] != SmitearWebGL.Core.PoolGroup.INVALID_INDEX;
	}
	,
	member : function( index )
	{
		$THROW( index < this._maxCount, "索引无效" );

		return this._memberList[index];
	}
}
);

SmitearWebGL.Core.PoolGroup.INVALID_INDEX = SmitearWebGL.Core.Math.MAX_INT_VALUE;
SmitearWebGL.Core.PoolGroup.CLEAR_HANDLE = function( h ) { h = SmitearWebGL.Core.PoolGroup.INVALID_INDEX };
SmitearWebGL.Core.PoolGroup.VALID_HANDLE = function( h ) { return ( h != SmitearWebGL.Core.PoolGroup.INVALID_INDEX ) };